<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-menu"></i>{{$route.name}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div>
            <div class="handle-box">
                <el-dialog :title="title" :visible.sync="dialogFormVisible">
                    <el-form :model="addForm" :rules="rules" ref="addForm">
                        <el-form-item label="发布时间" :label-width="formLabelWidth">
                            <el-date-picker v-model="addForm.publicAt" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
                            <el-input type="text" v-model="addForm.title" auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="副标题" :label-width="formLabelWidth" prop="subTitle">
                            <el-input type="text" v-model="addForm.subTitle" auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="简介" :label-width="formLabelWidth" prop="description">
                            <el-input type="text" v-model="addForm.description" auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="是否推荐" :label-width="formLabelWidth">
                            <el-select v-model="addForm.isTop" placeholder="请选择">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="内容" :label-width="formLabelWidth">
                            <!-- <el-input type="textarea" v-model="addForm.content" auto-complete="off"></el-input> -->
                            <editor @input="htmlOutput" :htmlContent="addForm.content"></editor>
                        </el-form-item>
                        <el-form-item label="分类" :label-width="formLabelWidth" prop="typeId">
                            <el-select v-model="addForm.typeId" placeholder="请选择">
                                <el-option
                                    v-for="item in typeList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="来源" :label-width="formLabelWidth">
                            <el-input type="text" v-model="addForm.origin" auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="作者" :label-width="formLabelWidth">
                            <el-input type="text" v-model="addForm.author" auto-complete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="图片" :label-width="formLabelWidth">
                            <el-upload
                                action=""
                                class="avatar-uploader" 
                                ref="upload"
                                accept="image/*"
                                :http-request="upload"
                                :show-file-list="false" 
                                :before-upload="beforeAvatarUpload"
                                v-loading.fullscreen.lock="fullscreenLoading" 
                            >
                                <img v-if="imageUrl" :src="imageUrl || ''" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="附件" :label-width="formLabelWidth">
                            <el-upload
                                action=""
                                multiple
                                :http-request="uploadFileRequest"
                                :on-remove="handleRemove"
                                :before-remove="beforeRemove"
                                :file-list="fileList"
                            >
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="add">确 定</el-button>
                    </div>
                </el-dialog>
                <el-input v-model="select_word" placeholder="输入文章标题" class="search"></el-input>
                <el-button type="primary" icon="search" @click="search">搜索</el-button>
                <el-button type="primary" @click="addNews">新增</el-button>
            </div>
            <div>
                <el-table :data="tableData" border fit>
                    <el-table-column label="发布时间" prop="publicAt" :formatter="timeFomatter"></el-table-column>
                    <el-table-column label="图片">
                        <template slot-scope="scope" fixed prop="img">
                            <img :src="scope.row.imgUrl" width="100%" height="100%" />
                        </template>
                    </el-table-column>
                    <el-table-column label="标题" prop="title"></el-table-column>
                    <el-table-column label="副标题" prop="subTitle" show-overflow-tooltip></el-table-column>
                    <el-table-column label="简介" prop="description" show-overflow-tooltip></el-table-column>
                    <el-table-column label="是否推荐" prop="isTop" :formatter="reccFomatter"></el-table-column>
                    <el-table-column label="内容" prop="content" show-overflow-tooltip></el-table-column>
                    <el-table-column label="类型" prop="typeId" :formatter="typeFomatter"></el-table-column>
                    <el-table-column label="来源" prop="origin"></el-table-column>
                    <el-table-column label="作者" prop="author"></el-table-column>
                    <el-table-column label="阅读量" prop="clickTimes"></el-table-column>
                    <el-table-column label="附件" prop="attachName"></el-table-column>
                    <el-table-column fixed="right" label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="put(scope.row)">编辑</el-button>
                            <el-button type="text" size="small" @click="del(scope.row)">删除</el-button>
                            <el-switch
                                v-model="scope.row.state === 1 ? true : false" 
                                active-color="#13ce66"
                                @change="switchChange(scope.row)"
                            >
                            </el-switch>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="block">
                <el-pagination @current-change="handleCurrentChange" 
                :current-page="page.number" 
                layout="total,  prev, pager, next, jumper" 
                :total="page.total">
                </el-pagination>
            </div>

        </div>
    </div>
</template>
<script>
import Editor from './../../components/common/Editor';
import { decision, uploadFile } from '../../server/getDate.js'
import { mapState, mapActions } from 'vuex'
import { dateFormatter, filterObj } from './../../utils/local.js'
const { listApi, allTypes, addApi, updateApi, deleteApi, disableApi } = decision
export default {
    data() {
        return {
            formLabelWidth: '120px',
            select_word: '',
            dialogFormVisible: false,
            fullscreenLoading: false,
            imageUrl: '',
            fileList: [],
            addForm: {},
            title: '',
            options: [{
                value: '0',
                label: '不置顶'
            }, {
                value: '1',
                label: '置顶'
            }],
            rules: {
                title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
                typeId: [{ required: true, message: '请选择分类', trigger: 'blur' }],    
                subTitle: [{ required: true, message: '请输入副标题', trigger: 'blur' }],
                description: [{ required: true, message: '请输入简介', trigger: 'blur' }]
            },
        }
    },
    created() {
        this.getTypeList()
        this.getList(1)
    },
    components: {
        Editor
    },
    computed: mapState({
        tableData: state => state.Decision.list,
        page: state => state.Decision.page,
        typeList: state => state.Decision.typeList
    }),
    methods: {
        ...mapActions(['saveList', 'saveTypes']),
        handleCurrentChange(val) {
            this.getList(val)
        },
        beforeAvatarUpload(file) {
            this.fullscreenLoading = true
        },
        upload(file) {
            this.fullscreenLoading = false
            let formData = new FormData()
            formData.append('fileName', file.file);
            formData.append('fileType', '1')
            uploadFile(formData, res => {
                this.fullscreenLoading = false
                if (res.code === '000000') {
                    this.imageUrl = res.result.storageName
                    this.addForm.imgUrl = this.imageUrl
                } else {
                    this.$message.error(res.message)
                }
            }, err => {
                this.fullscreenLoading = false
            })
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${ file.name }？`);
        },
        handleRemove(file, fileList) {
            this.fileList = this.fileList.filter(item => {
                return item.name !== file.name
            })
        },
        uploadFileRequest(value) {
            let formData = new FormData()
            formData.append('fileName', value.file);
            formData.append('fileType', '2')
            uploadFile(formData, res => {
                if (res.code === '000000') {
                    this.fileList.push({
                        name: res.result.originName,
                        url: res.result.storageName
                    })
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        htmlOutput(html) {
            this.addForm.content = html
        },
        getTypeList() {
            allTypes().then(res => {
                if (res.code === '000000') {
                    this.saveTypes(res)
                } else {
                    this.$message.error(res.message)
                }
            }, () => {
                this.$message.error('网络错误')
            })
        },
        timeFomatter(row) {
            return dateFormatter(row.publicAt)
        },
        reccFomatter(row) {
            return row.state === 0 ? '不置顶' : '置顶'
        },
        typeFomatter(row) {
            if (this.typeList.length === 0) {
                return '无'
            } else {
                let state = ''
                this.typeList.some(item => {
                    if (item.id === row.typeId) {
                        state = item.name
                    }
                })
                return state
            }
        },
        getList(number) {
            const params = {
                page: number,
                pageSize: 10
            }
            if (this.select_word !== '') {
                params.searchKey = this.select_word
            }
            listApi({ ...params }).then(res => {
                if (res.code === '000000') {
                    this.saveList({
                        ...res,
                        number
                    })
                } else {
                    this.$message.error(res.message)
                }
            }, () => {
                this.$message.error('网络错误')
            })
        },
        search() {
            this.getList(this.page.number)
        },
        del(row) {
            this.$confirm('此操作将永久删除该名称, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteApi({ ids: row.id }).then(res => {
                    if (res.code === '000000') {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getList(this.page.number)
                    } else {
                        this.$message.error(res.message)
                    }   
                }, err => this.$message.error(err.message))
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        put(row) {
            this.title = '编辑决策调研'
            this.dialogFormVisible = true
            this.addForm = filterObj(row)
            if (dateFormatter(row.publicAt)) {
                this.addForm.publicAt = dateFormatter(row.publicAt)
            }
            this.fileList = []
            if (row.attachName && row.attachUrl) {
                this.fileList.push({
                    name: row.attachName,
                    url: row.attachUrl
                })
            }
            this.imageUrl = ''
            if (row.imgUrl) {
                this.imageUrl = row.imgUrl
            }
        },
        addNews() {
            this.dialogFormVisible = true
            this.addForm = {}
            this.imageUrl = ''
            this.title = '新增决策调研'
            this.fileList = []
        },
        add() {
            this.$refs['addForm'].validate(valid => {
                if (valid) {
                   
                    if (this.fileList && this.fileList.length > 0) {
                        this.addForm.attachName = this.fileList[0].name
                        this.addForm.attachUrl = this.fileList[0].url
                    } else {
                        delete this.addForm.attachName
                        delete this.addForm.attachUrl
                    }
                    this.dialogFormVisible = false
                    if (this.addForm.id) {
                        updateApi({ ...this.addForm }).then(res => {
                            if (res.code === '000000') {
                                this.$message.success('修改成功')
                                this.getList(this.page.number)
                            } else {
                                this.$message.error(res.message)
                            }
                        }, () => {
                            this.$message.error('网络错误')
                        })
                    } else {
                        addApi({ ...this.addForm }).then(res => {
                            if (res.code === '000000') {
                                this.$message.success('添加成功')
                                this.getList(this.page.number)
                            } else {
                                this.$message.error(res.message)
                            }
                        }, () => {
                            this.$message.error('网络错误')
                        })
                    }
                }
            })
        },
        switchChange(row) {
            disableApi({ 
                ids: row.id, 
                state: row.state ? '0' : '1' 
            }).then(res => {
                if (res.code === '000000') {
                this.$message.success('修改成功')
                this.getList(this.page.number)
                } else {
                this.$message.error(res.message)
                }
            }, () => {
                this.$message.error('网络错误')
            })
        }
    }
};
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}

.block {
  text-align: center;
  margin-top: 1%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
